﻿// ****************************************************************************
// Copyright © Alexander Shakurin 2010
// ****************************************************************************
// Author: Alexander Shakurin
// Email: alexshakurin@gmail.com
// ****************************************************************************

using System.Windows;
using System.Windows.Interactivity;

namespace MvvmInteractivity.Behaviours
{
	/// <summary>
	/// Behaviour for closing window from viewmodels.
	/// </summary>
	public class CloseWindowFromViewModel : Behavior<Window>
	{
		public IClosableViewModel ViewModel
		{
			get { return (IClosableViewModel)GetValue(ViewModelProperty); }
			set { SetValue(ViewModelProperty, value); }
		}

		public static readonly DependencyProperty ViewModelProperty =
			DependencyProperty.Register("ViewModel",
				typeof(IClosableViewModel),
				typeof(CloseWindowFromViewModel));

		protected override void OnAttached()
		{
			var viewModel = ViewModel ?? AssociatedObject.DataContext as IClosableViewModel;

			if (viewModel != null)
			{
				viewModel.RequestClose += OnViewModelRequestClose;
			}
		}

		private void OnViewModelRequestClose(object sender, CloseEventArgs e)
		{
			if (e.DialogResult != null)
			{
				AssociatedObject.DialogResult = e.DialogResult;
			}
			else
			{
				AssociatedObject.Close();
			}
		}
	}
}